package com.emperor.service.impl;

import com.emperor.dto.PartnerSaveDto;
import com.emperor.dto.UserPartnerDto;
import com.emperor.entity.Partner;
import com.emperor.mapper.PartnerMapper;
import com.emperor.result.PageResult;
import com.emperor.service.PartnerService;
import com.emperor.vo.PartnerIdVo;
import com.emperor.vo.SkuClassPageVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
public class PartnerServiceImpl implements PartnerService {
    @Autowired
    private PartnerMapper partnerMapper;

    @Override
    public void updatePwd(Integer id, UserPartnerDto userPartnerDto) {
        partnerMapper.updatePwd(id, userPartnerDto.getNewPassword());
    }

    @Override
    public void save(PartnerSaveDto dto) {
        Partner partner = new Partner();
        BeanUtils.copyProperties(dto, partner);
        //设置密码
        partner.setPassword(DigestUtils.md5DigestAsHex(dto.getPassword().getBytes()));
        //设置状态为1
        partner.setStatus(1);
        //保存
        partnerMapper.save(partner);
    }

    @Override
    public SkuClassPageVo findAll(Integer pageIndex, Integer pageSize, String name) {
       //设置分页信息
      PageHelper.startPage(pageIndex, pageSize);
        //调用查询所有数据的方法
        List<Partner> list = partnerMapper.findAll(name);
        //将查询到的数据封装到Page中
        Page<Partner> p = (Page<Partner>) list;
        //计算总页数
        long l = (p.getTotal() / pageSize) + 1;
        //封装返回结果
        SkuClassPageVo build = SkuClassPageVo.builder().
                pageIndex(pageIndex).
                pageSize(pageSize)
                .totalPage((int) l).totalCount((int) p.getTotal())
                .currentPageRecords(new List[]{p.getResult()}).build();
        //返回封装结果
        return build;
    }

    @Override
    public PartnerIdVo getPartnerById(Integer id) {
        PartnerIdVo vo = partnerMapper.getPartnerById(id);
        return vo;
    }

    @Override
    public void updatePartner(Integer id, PartnerSaveDto dto) {
        Partner partner = new Partner();
        BeanUtils.copyProperties(dto, partner);
        partnerMapper.updatePartner(id, partner);
    }

    @Override
    public void deletePartner(Integer id) {
        partnerMapper.deletePartner(id);
    }

    @Override
    public Integer count() {
        return partnerMapper.count();
    }
}
